package com.fly.show;

import java.io.File;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;

public class TreeView
{
    private Display display;
    
    private Shell shell;
    
    private Tree tree;
    
    public TreeView()
    {
        super();
        display = new Display();
        shell = new Shell(display);
        shell.setLayout(new FillLayout(SWT.HORIZONTAL));
        shell.setSize(800, 600);
        Composite composite = new Composite(shell, SWT.NONE);
        composite.setLayout(new FillLayout(SWT.HORIZONTAL));
        tree = new Tree(composite, SWT.BORDER | SWT.FULL_SELECTION);
        addContent();
        
        // 设置默认居中
        Rectangle screeRec = display.getBounds();
        Rectangle shellRec = shell.getBounds();
        shellRec.height = Math.min(shellRec.height, screeRec.height);
        shellRec.width = Math.min(shellRec.width, screeRec.width);
        shell.setLocation((screeRec.width - shellRec.width) / 2, (screeRec.height - shellRec.height) / 2);
        shell.open();
        while (!shell.isDisposed())
        {
            if (!display.readAndDispatch())
            {
                display.sleep();
            }
        }
        display.dispose();
    }
    
    private void addContent()
    {
        File file = new File("D:\\HIFI\\");
        File[] files = file.listFiles();
        tree.setItemCount(0);
        for (int i = 0; i < files.length; i++)
        {
            TreeItem item = new TreeItem(tree, SWT.NONE);
            item.setText(files[i].getName());
            // 调用递归方法
            listFiles(files[i], item);
        }
        tree.setLinesVisible(true);
        tree.setHeaderVisible(true);
        {
            TreeColumn treeColumn = new TreeColumn(tree, SWT.NONE);
            treeColumn.setWidth(400);
            treeColumn.setText("PreView");
        }
    }
    
    /**
     * 递归方法
     * 
     * @param rootFile
     * @param item
     */
    public static void listFiles(File rootFile, TreeItem item)
    {
        File[] files = rootFile.listFiles();
        if (files != null && files.length > 0)
        {
            for (int i = 0; i < files.length; i++)
            {
                System.out.println(files[i].getName());
                TreeItem subItem = new TreeItem(item, SWT.None);
                subItem.setText(files[i].getName());
                listFiles(files[i], subItem);
            }
        }
    }
    
    public static void main(String[] args)
    {
        new TreeView();
    }
}